<?php

namespace app\admin\controller;

use app\admin\controller\statistics\History;
use app\admin\controller\statistics\SealApplyFragment;
use app\admin\controller\statistics\UsedFragment;
use app\admin\model\Picture;

class Statistics extends Common
{

    protected $company;

    protected $beforeActionList = [
        'getCurrentCompany',
        'loadingAllSeal'
    ];


    public function _initialize()
    {
        parent::_initialize();
    }

    use UsedFragment {
        usedIndex as public sealUse;
    }
    use SealApplyFragment {
        appFormIndex as public sealApply;
    }

    use History {
        historyIndex as public sealAuditHistory;
        show as public historyShow;
    }


    public function show($id)
    {
        $row = \app\admin\model\AppForm::with(['processFlows.user', 'user', 'seal', 'approval'])
            ->where("company_id", $this->company->id)
            ->find($id);
        if (!$row) {
            $this->error("资源不存在！");
        }
        if ($this->request->isAjax()) {
            $this->success("", null, $row);
        }
        $value = processToGroupSort($row->processFlows);

        $this->assign("processFlowGroups", $value);
        $this->assign("user", $row->user);
        $this->assign("seal", $row->seal);
        $this->assign("approval", $row->approval);
        $this->assign("attachments", []);
        if ($row->imgs) {
            $value1 = (new Picture())->getByIdIn(explode(",", $row->imgs));
            $this->assign("attachments", $value1);
        }
        if ($row->used_img) {
            $value1 = (new Picture())->getByIdIn(explode(",", $row->imgs));
            $this->assign("usedImg", $value1);
        }
        if($row->used_times>$row->frequency){
            $row->used_times=$row->frequency;
        }
        if($row->remaining_times<0){
            $row->remaining_times=0;
        }
        $this->assign("row", $row);
        return $this->fetch();
    }

    /**
     * 查看审核流程
     * @param $id
     */
    public function processFlows($id)
    {
        $entity = \app\admin\model\AppForm::with(['processFlows.user'])->find($id);
        if ($this->request->ext() == 'json') {
            $this->success("成功", null, processToGroupSort($entity->processFlows));
        }
        $this->assign('processFlowGroups', processToGroupSort($entity->processFlows));
        return $this->fetch();
    }

    protected function loadingAllSeal()
    {
        $sealModel = new \app\admin\model\Seal();
        $seals = $sealModel->where('company_id', $this->company['id'])->select();
        $this->assign('seals', $seals);
    }

}